package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CheckGroupServiceImpl implements CheckGroupService {


    @Autowired
    CheckGroupDao dao;

    @Override
    @Transactional
    public void add(Integer[] checkitemIds, CheckGroup checkGroup) {
        //添加检察组
        dao.add(checkGroup);
        // 维护中间表
        if (checkGroup.getId()!=null&&checkitemIds!=null&&checkitemIds.length>0){
            for (Integer checkitemId : checkitemIds) {
                dao.set(checkGroup.getId(),checkitemId);
            }

        }else {
            throw new RuntimeException("检查项和检查组的中间表维护失败");
        }

    }

    @Override
    public PageResult findPage(QueryPageBean q) {
         PageHelper.startPage(q.getCurrentPage(),q.getPageSize());

            Page<CheckGroup> page = dao.findByCondition(q.getQueryString());
        return new PageResult(page.getTotal(),page);
    }

    @Override
    public CheckGroup findById(Integer id) {

        return dao.findById(id);
    }

    @Override
    public Integer[] findCheckItemIdsByCheckGroupId(Integer id) {

        return dao.findCheckItemIdsByCheckGroupId(id);
    }

    @Override
    @Transactional
    public void edit(Integer[] checkitemIds, CheckGroup checkGroup) {
        // 修改检查组
        dao.edit(checkGroup);
        // 删除现有的关系
        dao.deleAssociation(checkGroup.getId());
        //添加现有的关系
        if (checkGroup.getId()!=null&&checkitemIds!=null&&checkitemIds.length>0){
            for (Integer checkitemId : checkitemIds) {
                dao.set(checkGroup.getId(),checkitemId);
            }
        }

    }

    @Override
    @Transactional
    public void delById(Integer id) {
        // 判断检查组是否被套餐项关联
        long count =  dao.findSetmealCountByCheckGroupId(id);
        if (count==0){
            dao.deleAssociation(id);
            dao.delById(id);
        }else {
            throw new RuntimeException("该组关联了套餐组,不能删除");
        }
    }

    @Override
    public List<CheckGroup> findAll() {
        return dao.findAll();
    }
}
